package com.yujie.security;

import com.alibaba.fastjson.JSON;
import com.yujie.common.CommonStatus;
import com.yujie.utils.ResultJson;
import com.yujie.utils.ThreadLocalUtil;
import com.yujie.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理springSecurity认证失败异常,和404异常
 */
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        ResultJson resultJson;
        //用于非前后端分离,静态文件404拦截
/*        if(response.getStatus()==404){
            resultJson=new ResultJson(404,"404","找不到资源");
            WebUtils.renderString(response,JSON.toJSONString(resultJson));
            return;
        }*/
        String key=CommonStatus.EXCEPTION.value();
        String var1 = (String) ThreadLocalUtil.get(key);

        if(ThreadLocalUtil.get(key) != null){
            resultJson= new ResultJson(401,"认证失败",var1);
            ThreadLocalUtil.remove(key);
        }else{
            resultJson= new ResultJson<>(401,"认证失败",e.getMessage());
        }
        WebUtils.renderString(response,JSON.toJSONString(resultJson));

    }
}
